package rsexplorer.utils;

import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

public class ClassResolver extends URLClassLoader {

    protected ArrayList<ClassResolvedListener> events;
    protected HashMap<String, Class<?>> loaded;

    public ClassResolver(URL[] url) throws Exception {
        super(url);

        events = new ArrayList<ClassResolvedListener>();
        loaded = new HashMap<String, Class<?>>();
    }

    public int size() {
        return loaded.size();
    }

    public void addResolveListener(ClassResolvedListener e) {
        events.add(e);
    }

    public void removeResolveListener(ClassResolvedListener e) {
        events.remove(e);
    }

    public Class<?>[] getClasses() {
        return (Class<?>[])loaded.values().toArray(new Class<?>[loaded.size()]);
    }

    public static boolean isSystemClass(Class<?> cls) {
        return (cls.getPackage() != null && cls.getPackage().getImplementationVendor() != null);
    }

    public static boolean isSystemObject(Object object) {
        Class<?> cls = object.getClass();

        return (cls.getPackage() != null && cls.getPackage().getImplementationVendor() != null);
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        if (!loaded.containsKey(name)) {
            Class<?> temp = super.loadClass(name);

            for (int i = 0; i < events.size(); i++)
                events.get(i).classResolved(temp);
        
            loaded.put(name, temp);

            return temp;
        } else {
            return loaded.get(name);
        }
    }
}
